﻿

/* Global constants. */
var MAPS_SCOPE = 'https://maps.google.com/maps/feeds/';
var MAPS_MAIN_FEED = 'https://maps.google.com/maps/feeds/maps/default/full';

var g_mapsService;  // google.gdata.maps.MapsService


function loadXML(xmlText) {
    var xmlDoc;
    if (window.ActiveXObject) {
        xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
        xmlDoc.async = false;
        xmlDoc.loadXML(xmlText);
    }
    else if (DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(xmlText, "text/xml");
    }
    else {
        return null;
    }
    return xmlDoc;
}

function setCookie() {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + 20)
    document.cookie = "g314-scope-0=scope=https%3A%2F%2Fmaps.google.com%2Fmaps%2Ffeeds%2F&token=2%2FpTC1UlR_QYibYGFHmwnceKmXKiq_QyPY9kPFQkqunow;expires=" + exdate.toString();
}
  
function eventHandler(node, eventName, listener) {
    if (node.addEventListener)
        return node.addEventListener(eventName, listener, false);
    else if (node.attachEvent)
        return node.attachEvent('on' + eventName, listener);

    return null;
} 
function login() {
    google.accounts.user.login(MAPS_SCOPE);
} 
function logout() {
    google.accounts.user.logout();
    window.location.reload();
}
 
function showGDataError(e) {
    $('#errors').html('Error: ' + (e.cause ? e.cause.statusText : e.message));
    $('#errors').css('display', '');
}
 
function hideErrors() {
    $('#errors').css('display', 'none');
}
 
function init() {
    //setCookie();
    var authSubToken = google.accounts.user.checkLogin(MAPS_SCOPE);
    if (!authSubToken) {
        $('#state-guest').css('display', '');
        return;
    } 

    $('#state-loggedin').css('display',  '');

    g_mapsService = new google.gdata.maps.MapsService(
      'com.google.mapsdatasamples.simple_simple');

//    if (map == null) {
//        defultMapOptions = {
//            zoom: 4,
//            center: new google.maps.LatLng(39.90555, 116.39147),
//            mapTypeId: google.maps.MapTypeId.ROADMAP,
//            mapTypeControl: true
//        };
//        map = new google.maps.Map($("#canvas").get(0), defultMapOptions);
//    }
    var dsrc = "https://maps.google.com/maps/feeds/features/212800177725253189507/0004a07859593181e6f23/full";
    g_mapsService.getMapEntry(dsrc, function (mapFeedRoot) {
        var dddd = mapFeedRoot;
        //g_mapsService.getFeatureFeed(mapFeedRoot.feed.entry.content.src, function (featureFeedRoot) 
        //{
        if (map) {
            var featureEntries = mapFeedRoot.feed.entry;
            for (var i = 0; i < featureEntries.length; i++) {
                var kml = featureEntries[i].content.$t;
                var xmlDoc = $(loadXML(kml));
                var icon = xmlDoc.find('href').text();
                var coordinate = xmlDoc.find('coordinates').text();
                var allCoors = coordinate.split(',');
                var position = new google.maps.LatLng(allCoors[1], allCoors[0]); 
                var maker = new google.maps.Marker({ icon: icon, map: map, position: position });
                if (i == 0) {
                    map.setCenter(position);
                } 
            }
        }
        //}, showGDataError);
    }, showGDataError);

    // Load a list of maps.
    var mapListNode = $('#map-list');
    mapListNode.html( '<li>Loading...</li>');

    g_mapsService.getMapFeed(MAPS_MAIN_FEED, function (mapFeedRoot) {
        mapListNode.html('');
        var mapEntries = mapFeedRoot.feed.getEntries();

        for (var i = 0; i < mapEntries.length; i++) {
            // Create the map list item and link.
            var mapEntryNode = document.createElement('li');
            var mapEntryLinkNode = document.createElement('a');
            mapEntryLinkNode.href = '#';
            // Use a closure for event handlers.
            eventHandler(mapEntryLinkNode, 'click', (function (content) {
                return function (evt) {
                    $(".maphref").attr("value", content.src);
                    loadFeatureFeed(content.src);
                };
            })
            (mapEntries[i].content)); // content.src is a feature feed href

            mapEntryLinkNode.appendChild(
            document.createTextNode(mapEntries[i].getTitle().$t));

            mapEntryNode.appendChild(mapEntryLinkNode);
            mapListNode.append(mapEntryNode);
        }
    }, showGDataError);
}
 
function loadFeatureFeed(featureFeedHref) {
    var featureListNode = $('#feature-list');
    featureListNode.html(  '<li>Loading...</li>');

    g_mapsService.getFeatureFeed(featureFeedHref, function (featureFeedRoot) {
        featureListNode.innerHTML = '';
        var featureEntries = featureFeedRoot.feed.getEntries();
        for (var i = 0; i < featureEntries.length; i++) {
            // Create the feature list item and link.
            var featureEntryNode = document.createElement('li');
            var featureEntryLinkNode = document.createElement('a');
            featureEntryLinkNode.href = '#';

            // Use a closure for event handlers.
            eventHandler( featureEntryLinkNode, 'click', (function (featureKml) {
                return function (evt) {
                    loadFeatureKml(featureKml);
                };
            })(featureEntries[i].getContent().$t)); 
            // getContent().$t is a KML
            // string.

            featureEntryLinkNode.appendChild( document.createTextNode(featureEntries[i].getTitle().$t));

            featureEntryNode.appendChild(featureEntryLinkNode);
            featureListNode.append(featureEntryNode);
        }
        if (map) {
            var featureEntries = featureFeedRoot.feed.getEntries();
            for (var i = 0; i < featureEntries.length; i++) {
                var kml = featureEntries[i].content.$t;
                var xmlDoc = $(loadXML(kml));
                var icon = xmlDoc.find('href').text();
                var coordinate = xmlDoc.find('coordinates').text();
                var allCoors = coordinate.split(',');
                var position = new google.maps.LatLng(allCoors[1], allCoors[0]);
                var maker = new google.maps.Marker({ icon: icon, map: map, position: position });
                if (i == 0) {
                    map.setCenter(position);
                }
            }
        }
    }, showGDataError);
}

/**
* Shows the given KML string in the feature KML text area.
*/
function loadFeatureKml(featureKml) {
    $('#feature-kml').attr('value' , featureKml);
}
